#include "upload_file.h"

#include "server_define.h"
#include <unordered_map>
#include <vector>
#include "../sql.h"

upload_file::upload_file(QObject *parent)
    : QObject{parent} {
}

void upload_file::startListen(unsigned short port) {
    if (mysql == nullptr) {
        mysql = new sql;
    }

    //分配内存空间
    fileserver = new QTcpServer(this);
    fileserver->listen(QHostAddress::Any, port);
    connect(fileserver, &QTcpServer::newConnection, [=]() {
        //取出建立好连接的套接字
        fileSocket = fileserver->nextPendingConnection();

        connect(fileSocket, &QTcpSocket::readyRead, this, [&]() {
            // 接收数据
            QByteArray buf = fileSocket->readAll();
            QStringList send_filenames = QString(buf).split("{##}");
            qDebug() << send_filenames;

            mysql->connect(MYSQL_SERVER_HOST, MYSQL_SERVER_PORT, MYSQL_USERNAME, MYSQL_PASSWORD, MYSQL_DB_NAME);
            auto sql_song = mysql->select_song_name_and_path(send_filenames[0]);
            auto sql_lrc = mysql->select_song_lrc_and_path(send_filenames[0]);
            mysql->disconnect();
            for (auto& kv : sql_song) {
                bool is_exist = false;
                for (auto& cur : send_filenames) {
                    if (!cur.endsWith(".mp3"))
                        continue;
                    if (cur.contains(kv.first)) {
                        is_exist = true;
                        break;
                    }
                }
                if (!is_exist) {
                    qDebug() << kv.second;
                    file_queue.push_back(kv.second);
                }
            }
            for (auto& kv : sql_lrc) {
                bool is_exist = false;
                for (auto& cur : send_filenames) {
                    if (!cur.endsWith(".lrc"))
                        continue;
                    auto cur_mp3 = cur;
                    cur_mp3 = cur_mp3.replace(".lrc", ".mp3");
                    if (cur_mp3.contains(kv.first)) {
                        is_exist = true;
                        break;
                    }
                }
                if (!is_exist) {
                    qDebug() << kv.second;
                    file_queue.push_back(kv.second);
                }
            }

            UploadFile();
        });
        connect(fileSocket, &QTcpSocket::disconnected, this, [=]() {
            qDebug() << "upload disconnected";
            //断开连接
            fileSocket->close();
            fileSocket->deleteLater();
            // emit recvOver();
        });

        connect(this, &upload_file::file_path, this, &upload_file::Upload);
        connect(this, &upload_file::finish, this, [&](){
            timer2 = new QTimer(this);
            timer2->start(800);
            connect(timer2, &QTimer::timeout, [=]() {
                timer2->stop(); //关闭定时器
                UploadFile(); //发送文件数据
            });
        });

        timer3 = new QTimer(this);
        connect(timer3, &QTimer::timeout, [=]() {
            timer3->stop(); //关闭定时器
            fileSocket->close(); //发送文件数据
        });
    });
}

void upload_file::UploadFile() {
    if (file_queue.empty()) {
        timer3->start(800);
        return;
    }
    QString file = file_queue.dequeue();
    qDebug() << file_queue.size();
    emit file_path(file);
}

void upload_file::Upload(QString path) {
    timer = new QTimer(this);
    connect(timer,&QTimer::timeout,[=]() {
        timer->stop(); //关闭定时器
        sendfileData(); //发送文件数据
    });

    file.close();
    file.setFileName(path);
    //获取文件信息
    QFileInfo info(path);
    filesize = info.size();//获取文件大小
    filename = info.fileName();//获取文件名
    sendfilesize = 0;
    //只读方式打开文件
    bool isOk = file.open(QIODevice::ReadOnly);
    if(isOk) {
        QString head = QString("%1##%2").arg(filename).arg(filesize);  // 创建文件头信息
        qint64 len = fileSocket->write(head.toUtf8());  // 发送头部信息
        if (len>0) {
            timer->start(20); // 防止tcp黏包问题,延时20ms
        } else {
            //发送失败
            file.close();
            filename.clear();
            filesize = 0;
            sendfilesize = 0;

        }
    } else {
        qDebug() << "open failed";
        file.close();
        filename.clear();
        filesize = 0;
        sendfilesize = 0;
        // emit finish();
        return;
    }

}

void upload_file::sendfileData() {
    qint64 len = 0;
    //读多少发多少
    do {
        char buf[4*1024] = {0}; // 每次发送的大小
        len = file.read(buf,sizeof(buf)); // 记录每行数据
        sendfilesize += len;
        fileSocket->write(buf,len); // 发送数据
    } while(len>0);

    qDebug() << sendfilesize << "  " << filesize << "  " << filename;

    if(sendfilesize == filesize) {
        file.close();
        filename.clear();
        filesize = 0;
        emit finish();
        qDebug() << "sendfilesize == filesize";
    } else {
        file.close();
        filename.clear();
        filesize = 0;
        sendfilesize = 0;
        emit finish();
    }
}
